package com.google.code.jholidays.events;

import java.util.Calendar;
import java.util.Date;

import com.google.code.jholidays.core.EventDescriptor;
import com.google.code.jholidays.events.parameters.Offset;
import com.google.code.jholidays.events.properties.DependentEventProperties;

/**
 * Represents dependent event. This event <b>does</b> have parent one
 * <p>
 * When event's date is calculated parent one is resolved first. Then
 * {@link Offset} added to that date and the result is considered to be final
 * dependent event's date
 * <p>
 * For example we do have parent event which occurs on the 7th day of January of
 * each year. If we create dependent event with +5 days offset from parent event
 * it will occur on the 12th of January each year
 * 
 * @see AbstractEvent
 * @see EventDescriptor
 * @see DependentEventProperties
 * @author tillias
 * 
 */
public class DependentEvent extends AbstractEvent {

    /**
     * Creates new event instance using given {@link DependentEventProperties}
     * 
     * @param properties
     *            Event properties
     * @throws IllegalArgumentException
     *             Thrown if properties parameter passed to constructor is null
     */
    protected DependentEvent(DependentEventProperties properties)
	    throws IllegalArgumentException {
	super(properties);
    }

    /**
     * {@inheritDoc}
     * <p>
     * This implementation resolves parent event's date first. Then it adds
     * offset to parent event date and returns this sum
     * 
     * @see #getOffset()
     */
    @Override
    public Date getDate(int year) {
	Date result = null;

	Date parentDate = getParent().getDate(year);

	if (parentDate != null) {
	    Calendar calendar = Calendar.getInstance();
	    calendar.setTime(parentDate);

	    calendar.add(Calendar.DATE, getOffset().getDaysCount());

	    result = calendar.getTime();
	}

	return result;
    }

    /**
     * Gets offset between parent event and this one
     * 
     * @return Offset between parent event and this one
     * @see Offset
     */
    protected Offset getOffset() {
	return ((DependentEventProperties) getProperties()).getOffset();
    }
}
